//
//  ViewController.m
//  dataGathering
//
//  Created by apple on 14-11-4.
//  Copyright (c) 2014年 shuili. All rights reserved.
//

#import "ViewController.h"
#import "FMDB.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    _passwordTextField.delegate = self;
    _nameTextField.delegate = self;
    NSLog(@"%@",self.title);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginToMainTableView:) name:@"loginFinished" object:nil];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)confirmLoginBlockReturn {
    UIView* loginContainerView = (UIView*)([[[self view] subviews] objectAtIndex:4]);
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect formSheetRect = loginContainerView.frame;
                         formSheetRect.origin.y -= 35;
                         loginContainerView.frame = formSheetRect;
                     }
                     completion:^(BOOL finished) {
                         
                     }];
}

- (void)loginToMainTableView:(NSNotification*)noti
{
    NSNumber *result = (NSNumber*)[noti object];
    if([result integerValue] == LoginResultSuccess)
    {
        [_nameTextField setText:@""];
        [_passwordTextField setText:@""];
        [self performSegueWithIdentifier:@"loginToMain" sender:self];
    } else if ([result integerValue] == LoginResultWrongInfo){
        NSLog(@"wrong");
        
        UIView* loginContainerView = (UIView*)([[[self view] subviews] objectAtIndex:4]);
        
        [UIView animateWithDuration:0.5
                         animations:^{
                             CGRect formSheetRect = loginContainerView.frame;
                             formSheetRect.origin.y += 35;
                             loginContainerView.frame = formSheetRect;
                         }
                         completion:^(BOOL finished) {
                             [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(confirmLoginBlockReturn) userInfo:nil repeats:NO];
                         }];
        
        
        
    } else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"服务器错误" message:@"服务器连接错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (IBAction)confirmLogin:(id)sender {
    
    //[self performSegueWithIdentifier:@"loginToMain" sender:self];
    //return;
    
    if(![[AFNetworkReachabilityManager sharedManager] isReachable]){
        
        int err;
        sqlite3 *db;
        FMDatabase *fmdb;
        NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:@"workset.sqlite"];
        
        err = sqlite3_open_v2([dbpath UTF8String], &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
        sqlite3_enable_load_extension(db, 1);
        
        fmdb = [FMDatabase databaseWithPath:dbpath];
        [fmdb setDB:db :dbpath];
        
        FMResultSet *rsCheckUserInfoQuery= [fmdb executeQuery:@"select * from user_info_table where name = ? and pwd = ?",[_nameTextField text],[_passwordTextField text]];
        if([rsCheckUserInfoQuery next]){
            
            [[NSUserDefaults standardUserDefaults] setObject:[rsCheckUserInfoQuery stringForColumn:@"name"] forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:[rsCheckUserInfoQuery stringForColumn:@"realname"] forKey:@"realname"];
            [[NSUserDefaults standardUserDefaults] setObject:[rsCheckUserInfoQuery stringForColumn:@"department"] forKey:@"department"];
            [rsCheckUserInfoQuery close];
            
            [self performSegueWithIdentifier:@"loginToMain" sender:self];
            
            return;
        } else {
        
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"账号信息错误" message:@"用户名或密码错误" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
            }];
            [alertController addAction:action];
            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }
    }
    
    [SVProgressHUD showWithStatus:@"登录中,请稍候" maskType:SVProgressHUDMaskTypeBlack];
    
#warning  temp comment
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"loginFinished" object:nil];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [LoginManager loginUsingUsername:@"wolf" andPassword:@"wolf"];

    });
    
    
    /*
    if(result == LoginResultServerError) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"服务器连接错误" message:@"服务器无法连接" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    } else if (result == LoginResultWrongInfo){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"用户名或密码错误" message:@"用户名或密码错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
     */
   

    //if([[_passwordTextField text] compare:@"123"] == NSOrderedSame && [[_nameTextField text] compare:@"123"] == NSOrderedSame)
    
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self confirmLogin:self];
    return YES;
}
@end
